<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    [type="file"] {
      width: 100px;
      height: 100px; 
      position: absolute;
      top: 0;
      left: 0;
      z-index: 100;
      opacity: 0;
    }

    div {
      position: relative;
      width: 100px;
      height: 100px;
    }
  </style>
</head>
<body>
  <!-- 
    1 file选择的文件被filereader读取，得到base64
    2 将的到的base64设置给img
    3 将img绘制到canvas
    4 canvas添加到页面上
  -->
  <div>
    +
    <input type="file">

    <script>
      var f = new FileReader()
      var input = document.querySelector('input')
      f.onload = function () {
        // 读取完成后
        var base64 = this.result
        // 创建img
        var img = new Image()
        img.onload = function () {
          // 创建canvas
          var canvas = document.createElement('canvas')
          canvas.width = 100
          canvas.height = 100
          
          var size = getImageSize(this)
          canvas.getContext('2d').drawImage(this, size.x, size.y, size.width, size.height, 0, 0, 100, 100)
          document.body.appendChild(canvas)
        }
        img.src = base64
      }
      
      input.onchange = function () {
        var file = this.files[0]
        f.readAsDataURL(file)
      }


      function getImageSize (img) {
        var width = img.width
        var height = img.height
        return width > height ? {
          x: width / 2 - height / 2,
          y: 0,
          width: height,
          height: height
        } : {
          x: 0,
          y: height / 2 - width / 2,
          width: width,
          height: width
        }
        /* if (width > height) {
          return {
            x: width / 2 - height / 2,
            y: 0,
            width: height,
            height: height
          }
        } else {
          return {
            x: 0,
            y: height / 2 - width / 2,
            width: width,
            height: width
          }
        } */
      }
    
    </script>
  </div>
</body>
</html>